package com.zhongkai.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.WebSocketIndBean;
import com.zhongkai.MessageTool;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.SellStockService;
import com.zhongkai.listener.RocketMqProducer;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Record3;
import com.zhongkai.model3.Sell;
import com.zhongkai.model3.Warehouse3;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;

/**
 * 销售出库
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class SellStockServiceImpl implements SellStockService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;

    /*    @Autowired
        private JmsTemplate jmsTemplate;

        @Resource
        private Destination topicDestination;*/
    @Autowired
    private RocketMqProducer rocketMqProducer;

    /**
     * 销售出库
     *
     * @param uuid     销售订单uuid
     * @param out_name 出库人员
     * @param out_uuid 出库人员uuid
     */
    @Override
    public ZhongkaiResult outStorage(String uuid, String out_name, String out_uuid) {
        if (StringUtils.isNullOrEmpty(uuid) || StringUtils.isNullOrEmpty(out_name) || StringUtils.isNullOrEmpty(out_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        final Sell sell;

        sell = (Sell) iBaseDao.get("from Sell se where se.sellUuid='" + uuid + "'");

        if (sell == null) {
            return ZhongkaiResult.build(400, "此订单不存在");
        } else if (sell.getSellStatus() != 2) {
            return ZhongkaiResult.build(400, "订单状态不合法");
        } else if ("2".equals(sell.getIsOut())) {
            return ZhongkaiResult.build(400, "订单已出库");
        } else if ("2".equals(sell.getSellRemove())) {
            return ZhongkaiResult.build(400, "订单已删除");
        }


        //公司产品库
        Warehouse3 warehouse = (Warehouse3) iBaseDao.get("from Warehouse3 wa where wa.warUuid='" + sell.getSetUuid() + "'");
        int count = sell.getSellCount();
        String m_uuid;
        //Warehouse warehouse = new Warehouse();//库存表
        if (warehouse == null) {

            return ZhongkaiResult.build(400, "库存中没有此产品");

        } else { //库存中有此商品

            m_uuid = warehouse.getWarUuid();
            Integer warCount1 = warehouse.getWarCount();

            if (warCount1 <= 0) {

                return ZhongkaiResult.build(400, "库存不足");
            }


            int counts = warehouse.getWarCount() - count;
            if (counts >= 0) {
                warehouse.setWarCount(counts);
            } else {
                return ZhongkaiResult.build(400, "库存不足");

            }


            sell.setOutName(out_name);
            sell.setOutUuid(out_uuid);

            long millis = new DateTime().getMillis(); //获取当前系统时间戳
            sell.setOutTime(millis);//出库时间
            sell.setIsOut("2");//1未出库 2出库

            Record3 record = new Record3(); //库存操作记录表
            //record.
            record.setWarUuid(m_uuid);
            record.setWarName(warehouse.getWarName());
            record.setIndUuid(sell.getSellUuid()); //订单编号
            record.setWarCount(String.valueOf(sell.getSellCount()));//操作数量
            record.setRecordUser(out_name);//出库人员姓名
            record.setUserId(out_uuid);//出库人员姓名
            record.setRecordTime(millis);//时间
            record.setRecordType("2"); //1入库 2出库
            iBaseDao.update(warehouse); //库存表
            iBaseDao.save(record); //出库记录单
            iBaseDao.update(sell);


            String dateTime = new DateTime(sell.getSellTime()).toString("yyyy-MM-dd HH:mm:ss");

            WebSocketIndBean indBean = new WebSocketIndBean();
            indBean.setUser_uuid(sell.getMemberUuid());
            indBean.setType("5");
            indBean.setContent("您于 " + dateTime + " 提交的" + sell.getSellName() + "订单申请,已出库");

            ObjectMapper mapper = new ObjectMapper();


            try {
                String json = mapper.writeValueAsString(indBean);
                byte[] bytes = json.getBytes("utf-8");
                rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.FWEB_DATE, bytes);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }


/*            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {

                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/
            return ZhongkaiResult.ok();

/*            Integer warCount = +count;
            warehouse.setWarCount(warCount);
          ;*/

        }
    }


    /**
     * 已审批列表
     */
    @Override
    public ZhongkaiResult listStorage(Integer page, Integer rows) {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Sell.class);
            detachedCriteria.add(Restrictions.eq("sellRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("sellStatus", 2)); //已审批列表
            detachedCriteria.addOrder(Order.desc("sellTime")); //根据传入的字段进行降序排序
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }
}
